<template>
  <!-- 登录部分 -->
  <div class="loginContainer" v-show="toggle">
    <el-image style="width: 420px; height: 420px" :src="loginUrl" fit="fill" />

    <div class="loginForm">
      <div class="title">User Login</div>

      <!-- 验证账号部分 -->
      <div class="accountInput" v-show="!verify">
        <el-input
          v-model="account"
          size="large"
          placeholder="Please Input Your Account"
          :prefix-icon="UserFilled"
        />

        <div>
          <div v-show="accountTips != ''">{{ accountTips }}</div>
          <el-button
            v-not-choose="accountLoading"
            plain
            :loading="accountLoading"
            :color="buttonColor"
            @click="verifyAccount"
          >
            验证账号
          </el-button>
        </div>
      </div>

      <!-- 密码部分 -->
      <div class="passwordInput" v-show="verify">
        <div>
          <el-avatar :size="60" :src="avatar" />
          <div>
            <div class="account">{{ account }}</div>
            <div class="nickname">
              <el-icon><Avatar /></el-icon> &nbsp; {{ nickname }}
            </div>
          </div>
        </div>

        <el-input
          v-model="password"
          size="large"
          placeholder="Please Input Your Password"
          type="password"
          show-password
          :prefix-icon="Lock"
        />
        <div>
          <div v-show="passwordTips != ''">{{ passwordTips }}</div>
          <el-button plain @click="cancelLogin"> Cancel </el-button>
          <el-button
            v-not-choose="passwordLoading"
            plain
            :loading="passwordLoading"
            :color="buttonColor"
            @click="login"
          >
            Login
          </el-button>
        </div>
      </div>

      <div class="toggle">
        <div @click="toggleSignUpPage">没有账号？注册</div>
      </div>
    </div>
  </div>

  <!-- 注册组件部分 -->
  <SignIn
    v-show="!toggle"
    :signupUrl="signupUrl"
    :togglePage="togglePage"
    :buttonColor="buttonColor"
  />
</template>

<script lang="tsx" setup>
import { reactive, ref, toRefs, defineComponent } from 'vue'
import { useRouter } from 'vue-router'
import { UserFilled, Avatar, Lock } from '@element-plus/icons-vue'
import loginUrl from '@/assets/image/login.png'
import signupUrl from '@/assets/image/signup.png'
import defaultAvatar from '@/assets/image/default-avatar.png'
import { loginApi, verifyAccountApi, regUserApi } from '@/request/api/master'
import styles from './login.module.less'
import {
  useLoginStore,
  useThemeStore,
  useUserInfoStore,
} from '@/features/store/store'
import { storeToRefs } from 'pinia'
import { sourceUrl } from '@/config/baseConfig'

const router = useRouter()

const { buttonColor } = storeToRefs(useThemeStore())

// 切换注册和登录
const toggle = ref<true | false>(true)

// 账号是否验证成功
const verify = ref<true | false>(false)

// 切换登录与注册页面
const togglePage = (val: true | false) => (toggle.value = val)
// 切换到注册页面
const toggleSignUpPage = () => {
  togglePage(false)
  cancelLogin()
}

// 账号相关
const state1 = reactive<{
  account: string
  accountTips: string
  accountLoading: true | false
  avatar: string
  nickname: string
}>({
  account: '',
  accountTips: '',
  accountLoading: false,
  avatar: defaultAvatar,
  nickname: '',
})
const { account, accountTips, accountLoading, avatar, nickname } =
  toRefs(state1)

// 验证账号
const verifyAccount = async () => {
  if (!account.value) return (accountTips.value = '账号不能为空！')

  accountLoading.value = true
  const res = await verifyAccountApi(account.value.trim())
  accountLoading.value = false

  if (res.code !== 200) return (accountTips.value = '没有查询到该账号！')

  accountTips.value = ''
  avatar.value = sourceUrl + res.data.avatar ?? ''
  nickname.value = res.data.nickname
  verify.value = true
}

// 密码相关
const state2 = reactive<{
  password: string
  passwordTips: string
  passwordLoading: true | false
}>({ password: '', passwordTips: '', passwordLoading: false })
const { password, passwordTips, passwordLoading } = toRefs(state2)

// 用户登录
const login = async () => {
  if (!password.value) return (passwordTips.value = '密码不能为空！')

  const a = account.value.trim()
  const p = password.value.trim()
  passwordLoading.value = true
  const res = await loginApi({ account: a, password: p })
  passwordLoading.value = false

  if (res.code !== 200) {
    passwordTips.value = '密码错误！'
    return useLoginStore().setStatusFalse()
  }

  window.localStorage.setItem('token', res.data as string)
  useLoginStore().getStatus()
  useUserInfoStore().getUserInfo()
  router.push('/homePage')
}

// 取消登录，清除信息
const cancelLogin = () => {
  account.value = ''
  accountTips.value = ''
  avatar.value = defaultAvatar
  nickname.value = ''
  password.value = ''
  passwordTips.value = ''
  verify.value = false
}

// 注册组件
const SignIn = defineComponent({
  props: {
    signupUrl: { type: String, default: '' },
    togglePage: { type: Function, default: '' },
    buttonColor: { type: String, default: '' },
  },
  setup(props) {
    const account = ref<string>('')
    const password = ref<string>('')
    const signupTips = ref<string>('')
    const signupLoading = ref<true | false>(false)

    // 用户注册
    const regUser = async () => {
      if (!account.value || !password.value)
        return (signupTips.value = '请将账号、密码补充完整')

      signupLoading.value = true
      const res = await regUserApi({
        account: account.value.trim(),
        password: password.value.trim(),
      })
      signupLoading.value = false

      if (res.code !== 200) return (signupTips.value = res.message)

      signupTips.value = '注册成功！'
      account.value = ''
      password.value = ''
    }

    // 切换页面
    const togglePage = () => {
      props.togglePage(true)
      signupTips.value = ''
      account.value = ''
      password.value = ''
    }

    return () => (
      <div class={styles.signinContainer}>
        <el-image
          style="width: 420px; height: 420px"
          src={props.signupUrl}
          fit="fill"
        />

        <div class={styles.signupForm}>
          <div class={styles.title}>User Sign Up</div>

          <el-input
            v-model={account.value}
            size="large"
            placeholder="Please Input Your New Account"
            prefix-icon={UserFilled}
          />

          <el-input
            v-model={password.value}
            size="large"
            placeholder="Please Set New Account Password"
            type="password"
            show-password
            prefix-icon={Lock}
          />

          <div>
            <div v-show="accountTips != ''">{signupTips.value}</div>
            <el-button
              v-not-choose={signupLoading.value}
              type="primary"
              plain
              loading={signupLoading.value}
              color={props.buttonColor}
              onClick={regUser}
            >
              Sign Up
            </el-button>
          </div>

          <div class={styles.toggle}>
            <div onClick={togglePage}>已有账号？登录</div>
          </div>
        </div>
      </div>
    )
  },
})
</script>

<style lang="less" scoped>
.loginContainer {
  width: 100%;
  min-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  > .loginForm {
    height: 360px;
    width: 420px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    box-shadow: 0 0 5px 1px #dad8d8e8;
    background-color: var(--theme-aside);
    position: relative;

    > * {
      padding-bottom: 16px;
      width: 70%;
      transition: 0.3s;
    }

    > .title {
      font-size: 24px;
      font-weight: bold;
      color: var(--theme-hover-label);
      user-select: none;
    }

    > .accountInput {
      > * {
        padding-bottom: 12px;
      }

      > div:nth-child(2) {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        > div:nth-child(1) {
          font-size: 14px;
          color: var(--theme-active-label);
          flex: 1;
        }
      }
    }

    > .passwordInput {
      > * {
        margin-bottom: 12px;
      }

      > div:nth-child(1) {
        display: flex;
        align-items: center;
        height: 80px;
        box-shadow: 0 0 2px 1px #dbdbdbde;
        border-radius: 6px;
        padding-left: 12px;
        > .el-avatar {
          margin-right: 12px;
        }

        .account,
        .nickname {
          font-weight: bold;
          color: var(--theme-hover-label);
          padding-bottom: 6px;
          display: flex;
          align-items: center;
        }
      }

      > div:nth-child(3) {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        > div:nth-child(1) {
          font-size: 14px;
          color: var(--theme-active-label);
          flex: 1;
        }
      }
    }

    > .toggle {
      position: absolute;
      bottom: 0px;
      right: 20px;
      display: flex;
      justify-content: flex-end;
      user-select: none;

      > div {
        &:hover {
          color: var(--theme-active-label);
          font-weight: bold;
        }
        cursor: pointer;
        font-size: 14px;
        color: var(--theme-hover-label);
      }
    }
  }
}
</style>
